package com.lee.auth.endpoint.verifier.third;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lee.auth.endpoint.verifier.ThirdVerifier;
import jodd.http.HttpRequest;
import jodd.http.HttpResponse;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.IOException;

import static java.lang.Integer.MIN_VALUE;
import static java.nio.charset.StandardCharsets.UTF_8;

/**
 * @author Lee HN
 * @date 2020/7/18 19:45
 */
@Service
@AllArgsConstructor
public class QQThirdVerifier implements ThirdVerifier {

    private final ObjectMapper objectMapper;

    private static final String raw_url = "https://graph.qq.com/user/get_user_info?oauth_consumer_key=%s&openid=%s&access_token=%s";

    private static final String oauth_consumer_key = "101913552";

    @Override
    public boolean verify(String openId, String token) {
        String url = String.format(raw_url, getOauthConsumerKey(), openId, token);
        HttpResponse response = HttpRequest.get(url).acceptEncoding(UTF_8.name()).send();
        String body = response.bodyText();
        JsonNode readNode;
        try {
            readNode = objectMapper.readTree(body);
        } catch (IOException e) { return true; }
        int ret = readNode.path("ret").asInt(MIN_VALUE);
        return ret != 0;
    }

    @Override
    public int getProvider() {
        return QQ;
    }

    protected String getOauthConsumerKey() {
        return oauth_consumer_key;
    }

}
